#include "CLink/Router/RegexRouteHandler.h"
#include "CLink/error/ErrorHandler.h"

#include <Poco/URI.h>

namespace CLink
{
namespace Router
{

RegexRouteHandler::RegexRouteHandler(const std::string &pathPattern,
                                        const std::string &method,
                                        HandlerFunction handler,
                                        int priority)
    : BaseRouteHandler(pathPattern, method, priority), m_handler(handler)
{
}

bool RegexRouteHandler::handle(RequestContext &context)
{
    try
    {
        // 提取路由参数
        if (getMethod() != Poco::Net::HTTPRequest::HTTP_POST && getMethod() != Poco::Net::HTTPRequest::HTTP_PUT)
        {
            // 验证查询参数
            if (!validateQueryParams(context))
            {
                throw CLink::Error::CLinkException(CLink::Error::ErrorCode::INVALID_ARGUMENT, "Invalid query parameters");
            }

            auto dynamicParams = extractDynamicParams(context);
            auto queryParams = extractQueryParams(context);
            // 合并参数到context.params
            context.dynamicParams.swap(dynamicParams);
            context.queryParams.swap(queryParams);
        }

        // 调用处理函数
        if (m_handler)
        {
            m_handler(context);
            return true;
        }

        return false;
    }
    catch (const CLink::Error::CLinkException &e)
    {
        // 重新抛出错误，让错误处理器处理
        throw;
    }
    catch (const std::exception &e)
    {
        // 将其他异常转换为Error对象
        throw CLink::Error::CLinkException(CLink::Error::ErrorCode::INTERNAL_ERROR, e.what());
    }
}

bool RegexRouteHandler::matches(const RequestContext &context) const
{
    const auto &request = context.request;
    // 检查HTTP方法是否匹配
    if (m_method != request.getMethod())
    {
        return false;
    }

    // 获取请求路径
    Poco::URI uri(request.getURI());
    std::string path = uri.getPath();

    // 使用正则表达式匹配路径
    std::smatch matches;
    return std::regex_match(path, matches, m_pathRegex);
}

RegexRouteHandler &RegexRouteHandler::setHandler(HandlerFunction handler)
{
    m_handler = handler;
    return *this;
}

RegexRouteHandler &RegexRouteHandler::addNamedGroup(const std::string &name)
{
    m_groupNames.push_back(name);
    return *this;
}

std::vector<std::string> RegexRouteHandler::extractCaptureGroups(
    const RequestContext &context) const
{
    std::vector<std::string> groups;

    const auto &request = context.request;
    // 获取请求路径
    Poco::URI uri(request.getURI());
    std::string path = uri.getPath();

    // 使用正则表达式匹配路径
    std::smatch matches;
    if (std::regex_match(path, matches, m_pathRegex))
    {
        // 跳过第一个匹配项（整个字符串）
        for (size_t i = 1; i < matches.size(); ++i)
        {
            groups.push_back(matches[i].str());
        }
    }

    return groups;
}

} // namespace Router
} // namespace CLink